{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义测试数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test=[1,2,3,4,5,6,7]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "计算调和平均数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def harmonic_mean(data):\n",
    "    total=0\n",
    "    for i in data:\n",
    "        if i==0: #处理包含0的情况\n",
    "            return 0\n",
    "        total+=1/i\n",
    "    return len(data)/total"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.6997245179063363\n"
     ]
    }
   ],
   "source": [
    "print(harmonic_mean(data_test))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6.594085551052818 —— 83.71428571428571\n",
      "2.8455284552845534 —— 17.285714285714285\n",
      "0 —— 3.857142857142857\n"
     ]
    }
   ],
   "source": [
    "import numpy\n",
    "print(harmonic_mean([1,95,96,97,98,99,100]),'——',numpy.mean([1,95,96,97,98,99,100]))\n",
    "print(harmonic_mean([1,2,3,4,5,6,100]),'——',numpy.mean([1,2,3,4,5,6,100]))\n",
    "print(harmonic_mean([0,2,3,4,5,6,7]),'——',numpy.mean([0,2,3,4,5,6,7]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
